package com.pureut.socket.util;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.pureut.socket.domain.MessageReminder;
import com.pureut.socket.server.WebSocketToUser;
import com.sale.common.core.exception.GlobalException;
import com.sale.system.api.RemoteWorkbenchMessageService;
import com.sale.system.api.domain.vo.SysWorkbenchMessageVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description mq订阅消息
 * @Date 22-12-22
 * @Author hl
 **/
@Service
public class RocketMqSubscribe {

    @Value("${rocketmq.name-server}")
    private String mqServer;

    @Value("${producer.group}")
    private String mqGroup;


    @Resource
    private WebSocketToUser webSocketToUser;

    @DubboReference
    RemoteWorkbenchMessageService remoteWorkbenchMessageService;


    @PostConstruct
    public void rocketMqSubscribe() throws MQClientException {
        //0.创造消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("reminder");
        //1.给消费者设置名称服务器
        consumer.setNamesrvAddr(mqServer);
        //2.订阅的主题和子表达式是什么
        consumer.subscribe(mqGroup, "*");
        //3.设置从哪里开始消费消息
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //4.注册消息监听器,参数是并发消息监听器，Concurrently并发的意思
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                //逐条消费消息
                for (MessageExt msg : msgs) {
                    //输出消息的消费时间
                    System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
                    String syn = new String(msg.getBody());
                    if (StringUtils.isNotBlank(syn)) {
//                        try {
                            MessageReminder reminder = JSON.parseObject(syn, MessageReminder.class);
                            //向客户端发送消息
//                            String userId = reminder.getUserIds();
//                            String[] userIdS = userId.split(",");
                            //消息提醒集合
                            ArrayList<SysWorkbenchMessageVo> workMessageList = new ArrayList<>();
//                            if (userIdS.length > 1) {
//                                for (String u : userIdS) {
                                    //往消息提醒表中插入数据
                                    SysWorkbenchMessageVo sysWorkbenchMessageVo = new SysWorkbenchMessageVo();
                                    sysWorkbenchMessageVo.setMessageType(reminder.getMessageType());
                                    sysWorkbenchMessageVo.setMessageContent(reminder.getMessage());
                                    sysWorkbenchMessageVo.setWarnTime(new Date());
                                    sysWorkbenchMessageVo.setTenantId(reminder.getTenantId());
                                    sysWorkbenchMessageVo.setReadMark(2);//未读
//                                    sysWorkbenchMessageVo.setUserId(Long.valueOf(u));
                                    sysWorkbenchMessageVo.setStock(reminder.getStock());
                                    workMessageList.add(sysWorkbenchMessageVo);
//                                }
//                            } else {
//                                //往消息提醒表中插入数据
//                                SysWorkbenchMessageVo sysWorkbenchMessageVo = new SysWorkbenchMessageVo();
//                                sysWorkbenchMessageVo.setMessageType(reminder.getMessageType());
//                                sysWorkbenchMessageVo.setMessageContent(reminder.getMessage());
//                                sysWorkbenchMessageVo.setWarnTime(new Date());
//                                sysWorkbenchMessageVo.setReadMark(2);//未读
//                                sysWorkbenchMessageVo.setUserId(Long.valueOf(userId));
//                                sysWorkbenchMessageVo.setStock(reminder.getStock());
//                                workMessageList.add(sysWorkbenchMessageVo);
//                            }
                            boolean b = remoteWorkbenchMessageService.insertWork(workMessageList);
                            if (!b) {
                                throw new GlobalException("服务调用失败");
                            }

//                            if (userIdS.length > 1) {
//                                for (String u : userIdS) {
//                                    webSocketToUser.sendToUser(syn, u);
//                                }
//                            } else {
//                                webSocketToUser.sendToUser(syn, userId);
//                            }
                            //    webSocketToUser.sendToUser(reminder.getMsg(), reminder.getUserId());
//                        } catch (IOException e) {
//                            throw new RuntimeException(e);
//                        }
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.开启消费者
        consumer.start();
        System.out.println("消费者已开启消费---");
    }
}
